Magic commands

The magic commands, or magics, are handy commands built into the IPython kernel that make it easy to perform particular tasks, for example, interacting Python’s capabilities with the operating system, another programming language, or a kernel.

IPython provides two categories of magics: line magics and cell magics. Line magics operate on a single line of input and are denoted by a single percent sign (%). Cell magics can operate on multiple lines of input and are denoted by two percent signs (%%).

The pystata Python package provides three magic commands to interact with Stata from within the IPython environment: stata, mata, and pystata.

  • stata: Execute Stata commands

  • mata: Execute Mata code

  • pystata: Configure and display current system information

The three magic commands will be automatically loaded when the Stata environment is initialized. See Configuration for instructions on how to configure the pystata package within Python and initialize Stata.

Note that the magic commands can only be used in an IPython environment, such as Jupyter Notebook. They will not work in a non-IPython environment, like the Windows Command Prompt, the macOS terminal, the Unix terminal, a Python script file, etc. However, you can use the API functions defined in the config and stata modules of the pystata package to replicate the functionalities of those magic commands. See API functions for more information.

The IPython environment is the most flexible way to interact between Stata and Python because you can use the magic commands, the config and stata modules, and the Stata Function Interface (sfi) module all in one workspace.

The code shown in the following sections was run in a Jupyter Notebook, but you may choose to run it in some other IPython environment. For more examples of the magic commands, see Examples.